package com.lxw.nonghe.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class LogFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化方法，容器启动时调用一次
        System.out.println("LogFilter 初始化完成");
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        // 转换为HttpServletRequest以获取更多信息
        HttpServletRequest httpRequest = (HttpServletRequest) request;

        // 记录请求开始时间
        long startTime = System.currentTimeMillis();

        // 获取请求基本信息
        String requestURI = httpRequest.getRequestURI();
        String method = httpRequest.getMethod();
        String remoteAddr = httpRequest.getRemoteAddr();

        // 打印请求开始日志
        System.out.printf("[%s] 请求开始 %s %s 客户端IP: %s%n",
                Thread.currentThread().getName(), method, requestURI, remoteAddr);

        try {
            // 放行请求，继续处理链
            chain.doFilter(request, response);
        } finally {
            // 计算耗时
            long duration = System.currentTimeMillis() - startTime;

            // 打印请求完成日志
            System.out.printf("[%s] 请求完成 %s %s 耗时: %dms%n",
                    Thread.currentThread().getName(), method, requestURI, duration);
        }
    }

    public void destroy() {
        // 销毁方法，容器关闭时调用
        System.out.println("LogFilter 已销毁");
    }
}
